/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.satyam.swingvalidator.core;

import java.awt.Container;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JTextField;

/**
 *
 * @author Satyam
 */
public class ValidationGroup implements PropertyChangeListener{
    private boolean groupValidity; 
    private List<ValidationItem> validationItems;
    private final Container parent;
    private final PropertyChangeSupport groupValiditySupport;  
    
    
    public ValidationGroup(Container parent){
        this.parent = parent;
        this.groupValidity = false;
        this.validationItems = new ArrayList<ValidationItem>();
        this.groupValiditySupport = new PropertyChangeSupport(this);
        this.groupValiditySupport.addPropertyChangeListener(this);
        ((Validable) parent).reportStatus(false);
    }
    
    public void add(JComponent c, AbstractValidator validator,  boolean isMandatory){
        setupValidationItem(c, validator, isMandatory);
        setupValidator(c, validator);
    }
    
    private void setupValidationItem(JComponent c, AbstractValidator validator,  boolean isMandatory){
        ValidationItem item = new ValidationItem(c, isMandatory, this);
        validator.setValidationItem(item);
        validationItems.add(item);
    }
    
    private void setupValidator(JComponent c, AbstractValidator validator){
        JTextField textComponent = (JTextField)c;
        textComponent.setInputVerifier(validator);
    }
    
    public void updateGroupValidationStatus(){
        for(int i = 0; i< validationItems.size(); i++){
            if(validationItems.get(i).getValidity() == false){
                setGroupValidity(false);
                return;
            }
        }
        setGroupValidity(true);
    }

    public void setGroupValidity(boolean groupValidity) {
        boolean oldValidity = this.groupValidity;
        this.groupValidity = groupValidity;
        groupValiditySupport.firePropertyChange("groupValidity", oldValidity, groupValidity);
    }
    
    public boolean getGroupValidity(){
        return groupValidity;
    }

    public Container getParent() {
        return parent;
    }

    public List<ValidationItem> getValidationItems() {
        return validationItems;
    }

    public void propertyChange(PropertyChangeEvent evt) {
        ((Validable) parent).reportStatus((Boolean)evt.getNewValue());
    }
}
